package com.mall.order.server.service.impl;

import com.mall.common.core.domain.Result;
import com.mall.common.redis.service.RedisService;
import com.mall.order.common.dto.OrderRequest;
import com.mall.order.common.dto.Sku;
import com.mall.order.server.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    private static final String QUEUE_NAME = "order_queue_ybz"; // 定义消息队列名称
    private static final DefaultRedisScript<Long> STOCK_DEDUCT_SCRIPT;

    static {
        STOCK_DEDUCT_SCRIPT = new DefaultRedisScript<>();
        STOCK_DEDUCT_SCRIPT.setLocation(new ClassPathResource("lua/stock_deduct.lua"));
        STOCK_DEDUCT_SCRIPT.setResultType(Long.class);
    }


    // 发送下单请求的方法-MQ
    @Override
    public Result planOrder(OrderRequest orderRequest) {
        String orderSn = createOrderSn();
        orderRequest.setOrderSn(orderSn);
        // 发送消息到队列
        rabbitTemplate.convertAndSend(QUEUE_NAME, orderRequest);
        //返回成功信息提示用户订单正在处理中
        return Result.success( "订单正在处理中请稍后!",orderSn);
    }



    //lua脚本减去库存
    public Result reduceStocks(List<Sku> skuList) {

        // 构造 Redis 脚本参数
        List<String> keys = new ArrayList<>();
        List<Integer> args = new ArrayList<>();


        for (Sku sku : skuList) {
            keys.add(sku.getProductId());
            args.add(sku.getQuantity());
        }

        // 执行 Lua 脚本
        Long result = (Long) redisService.redisTemplate.execute(
                STOCK_DEDUCT_SCRIPT,
                keys,
                args.toArray()
        );
        // 断言结果
        //处理返回值
        if (result==0) {
            return Result.success("库存扣减成功");
        } else if (result==3) {
            return Result.error("库存不足");
        } else if (result==2) {
            return Result.error("无效的扣减数量");
        } else if (result==1) {
            return Result.error("参数数量不匹配");
        }
        return Result.error("系统繁忙，稍后再试");
    }

    /**
     * 轮询查询redis检查订单状态
     * @param orderSn
     * @return
     */
    @Override
    public Result PollingFindRedis(String orderSn) {
        Boolean b = redisService.hasKey("Plan_Order:" + orderSn);
        if(true == b){
            return Result.success("订单创建成功，请尽快支付");
        }else {
            return Result.error();
        }
    }


    //生成订单号
    private String createOrderSn() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Random random = new Random();
        // 获取当前时间戳并格式化
        String timestamp = sdf.format(new Date());
        // 生成一个三位数的随机数，范围是000到999
        int randomNum = random.nextInt(999);
        // 补齐三位数
        String paddedRandomNum = String.format("%03d", randomNum);
        // 组合时间戳和随机数生成订单号
        return timestamp + paddedRandomNum;
    }

}
